<?php

/**
 * This is the model class for table "ham_contact".
 *
 * The followings are the available columns in table 'ham_contact':
 * @property integer $id
 * @property string $email
 * @property string $full_name
 * @property string $title
 * @property string $phone
 * @property string $address
 * @property integer $status
 * @property integer $unsubscribe
 * @property string $created_at
 * @property integer $created_by
 *
 * The followings are the available model relations:
 * @property User $createdBy
 * @property ContactCampaign[] $contactCampaigns
 * @property ContactCustomValue[] $contactCustomValues
 * @property GroupContact[] $groupContacts
 */
class Contact extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Contact the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ham_contact';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('email', 'required', 'message' => Yii::t('main','Vui lòng nhập email')),
			array('full_name', 'required', 'message' => Yii::t('main','Vui lòng nhập họ tên')),
			array('email', 'length', 'max'=>255),
			array('email', 'email', 'message' => Yii::t('main','Địa chỉ email không hợp lệ')),
			array('full_name', 'length', 'max'=>200),
			array('phone', 'length', 'max'=>20),
			array('address', 'length', 'max'=>200),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, email, full_name, phone, address, status, unsubscribe, created_at, created_by', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'createdBy' => array(self::BELONGS_TO, 'User', 'created_by'),
			'contactCampaigns' => array(self::HAS_MANY, 'ContactCampaign', 'contact_id'),
			'contactCustomValues' => array(self::HAS_MANY, 'ContactCustomValue', 'contact_id'),
			'groupContacts' => array(self::HAS_MANY, 'GroupContact', 'contact_id'),
		);
	}

	public function beforeSave(){
		if($this->isNewRecord){
			$this->created_at = date('Y-m-d H:i');
		}
		return parent::beforeSave();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'email' => 'Email',
			'full_name' => Yii::t('main','Họ tên'),
			'title' => Yii::t('main','Danh xưng'),
			'phone' => Yii::t('main','Điện thoại'),
			'address' => Yii::t('main','Địa chỉ'),
			'status' => Yii::t('main','Hoạt động'),
			'unsubscribe' => 'Unsubscribe',
			'created_at' => 'Created At',
			'created_by' => 'Created By',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('full_name',$this->full_name,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('unsubscribe',$this->unsubscribe);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('created_by',$this->created_by);
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Function to get list tile for dropdown and get value
	 */
	public function getTitle($name = null){
		$arr = array(
			''	=> '',
			'ong' => Yii::t('main','Ông'),
			'ba' => Yii::t('main','Bà'),
			'anh' => Yii::t('main','Anh'),
			'chi' => Yii::t('main','Chị'),
			'em' => Yii::t('main','Em'),
		);
		if(!empty($name)){
			return (isset($arr[$name]))?$arr[$name]:'';
		}
		return $arr;
	}

	/**
	 * Function to insert/update contact
	 */
	public function updateContact(){
		$result = array('msg' => '', 'success' => false);
		if($this->isNewRecord){
			$this->created_by = Yii::app()->user->getId();
			$result['success'] = $this->insert();
			$result['msg'] = Yii::t('main', 'Tạo mới thành công!');
		}else{
			$result['success'] = $this->update();
			$result['msg'] = Yii::t('main', 'Cập nhật thành công!');
		}
		return $result;
	}

	/**
	 * Function to delete Contact
	 */
	public function deleteContact(){
		$transaction= $this->dbConnection->beginTransaction();
		$result = true;
		try{
			foreach($this->groupContacts as $gc){
				if(!$gc->delete()){
					$result = false;
					break;
				}
			}
		    if($result === true){
		    	$result = $this->delete();
		    }

		    if($result === true){
		        $transaction->commit();
		    }else{
		        $transaction->rollback();
		    }
		    return $result;
		}
		catch(Exception $e)
		{
		    $transaction->rollback();
		    return false;
		}		
	}

	// provider for add contact to group
	public function providerContactsToAddGroup($groupId){
		$group = Group::model()->findByPk($groupId);
		if(!is_object($group)) return;
		$contactsId = array_keys(CHtml::listData($group->groupContacts,'contact_id','1'));
		$dataProvider = new CActiveDataProvider('Contact');
		$dataProvider->pagination->setPageSize(8);
		$dataProvider->criteria->addNotInCondition('id', $contactsId);
		return $dataProvider;
	}

	public function providerContactsInGroup($groupId){
		$group = Group::model()->findByPk($groupId);
		if(!is_object($group)) return;
		$contactsId = array_keys(CHtml::listData($group->groupContacts,'contact_id','1'));
		$dataProvider = new CActiveDataProvider('Contact');
		if(empty($contactsId)){
			$dataProvider->criteria->addCondition('0=1');
		}else{
			$dataProvider->criteria->addInCondition('id', $contactsId);
		}
		return $dataProvider;
	}

	/**
	 * Function to get all groups which contact belong
	 */
	public function getGroupsBelong($returnHtml = false){
		$groups = array();
		$str = "";
		foreach($this->groupContacts as $g){
			$groups[] = array('id' => $g->group->id, 'name' => $g->group->name);
			$str .= "<li>-&nbsp;".$g->group->name."</li>";
		}
		$str = (empty($groups))?'':'<ul>'.$str.'</ul>';
		if($returnHtml === true){
			return $str;			
		}else{
			return $groups;
		}
	}
}